#!/bin/bash

#***********************************************************************************
#* Code license:  GNU General Public License v3                                    *
#* Main page:     https://code.google.com/p/library-cross-platform/                *
#* Issue tracker: https://code.google.com/p/library-cross-platform/issues/list     *
#***********************************************************************************


COMPILER=
CFLAGS=
COMPILE_DIR=
CURENT_DIR=
OUT_DIR=
FILE_LIST=
DEFINE=
INCLUDE_DIR=

# define usage function
function usage(){
	echo "Usage: not defined yet :("
	exit 1
}
 

function find_files_2_build() {
  FILE_LIST=( $(find $COMPILE_DIR -type f \( -name "*.cpp" -o -name "*.c" \) -a \! \( -name "~*" -o -name ".*" \)))
}


#########################################################
################### MAIN SECTION ########################

### check for arguments
if [ $# -eq 0 ] ; then
   usage "No arguments"
fi

COMPILER=$1
CFLAGS=$2
DEFINE=$3
INCLUDE_DIR=$4
COMPILE_DIR=$5
OUT_DIR=$6
CURENT_DIR=`pwd`

echo "===================================================================="
echo "compiler: " $COMPILER
echo "cflags: " $CFLAGS
echo "define: " $DEFINE
echo "include dir: " $INCLUDE_DIR
echo "compile dir: " $COMPILE_DIR
echo "out dir: " $OUT_DIR
echo "===================================================================="

find_files_2_build

element_count_max=${#FILE_LIST[@]}
element_count=0
status_log=/tmp/compile_result.$$

echo "### START BUILD " $element_count_max "FILES"

#for element in $(seq 0 $((${#FILE_LIST[@]} - 1)))
while [ "$element_count" -lt "$element_count_max"]
do
  echo "#########################################################################"
  echo "COMPILER: " $COMPILER "CFLAGS: " $CFLAGS "DEFINE: " $DEFINE
  echo "INCLUDE_DIR: " $INCLUDE_DIR
  echo "in: " $cfile "out: " $ofile
  cfile="${FILE_LIST[$element_count]}"
  ofile=${cfile%\.*}".o"

  echo $COMPILER $CFLAGS $DEFINE $INCLUDE_DIR "-c" $cfile "-o" $ofile
  { $COMPILER $CFLAGS $DEFINE $INCLUDE_DIR "-c" $cfile "-o" $ofile || echo $? > $status_log; } 2>&1 | tee -a $status_log;
  
  if [ -r $status_log ] ; then
    status=`cat $status_log`
    if [[ $status == "1" ]] ; then
      /bin/rm -rf $status 2/dev/null
      echo "##### BUILD FAILED. EXIT CODE: " $status " #####"
      exit $status
    fi
  fi
  let "index = $index  + 1"
done

echo "#########################################################################"

 

